<template>
  <div> 
    <a-button type="primary" @click="newMemberData()" style="margin-bottom:10px;cursor: pointer;">新增</a-button>
    <div class="box-header">
      <span>序号</span>
      <span>计量单位</span>
      <span>单位进制</span>
      <span>是否基本单位</span>
      <span>规格</span>
      <span>单位单价</span>
      <span>操作</span>
    </div>
    <div class="content-box">
      <div v-for="(item,index) in data" :key="index" class="box-content">
        <span>{{index+1}}</span>
        <span><a-input v-model.trim="item.unitMeasurement"  :class="item.unitMeasurementBorder?'colorBorder':''"  @change="valChange(item,index,'unitMeasurement')" allow-clear placeholder="计量单位"></a-input></span>
        <span><a-input-number v-model.trim="item.systemRatio"  :class="item.systemRatioBorder?'colorBorder':''" allow-clear @change="valChange(item,index,'systemRatio')" placeholder="单位进制"></a-input-number></span>
        <span>
          <a-select   
            placeholder="请选择"
            v-model.trim="item.isBasicUnit"
            @change="valChange(item.isBasicUnit,index,'isBasicUnit')"
          > 
            <a-select-option :value="0">
              <div>否</div>
            </a-select-option>
            <a-select-option :value="1">
              <div>是</div>
            </a-select-option>
          </a-select>
        </span>
        <span><a-input allow-clear v-model.trim="item.spec"  @change="valChange(item,index,'spec')" :class="item.specBorder?'colorBorder':''" placeholder="规格"></a-input></span>
        <span><a-input-number  allow-clear  :min="0" v-model.trim="item.price"   @change="valChange(item.price,index,'price')"  placeholder="单价"  ></a-input-number></span>
        <span style="color:#3ea2ff;cursor: pointer;" @click="removeList(item,index)">删除</span>
      </div>
      
    </div>
  </div>
     
</template>

<script>
import { UpdateContact } from '@/api/customer/customer'
import { getCustomerConsult } from '@/api/customer/customer'
import { callPhone } from '@/api/components/callPhone'
import Bus from '@/utils/bus'
import { mapState } from 'vuex'
export default {
  name: 'ContactTable',
  props: {
    ContactList: {
      type: Array,
      default: () => [],
    },
    customerCrmId: {
      type: String,
      default: '',
    },
    customer: {
      type: Object,
      default: () => {},
    },
     
    formData: {
      type: Array,
      default: () => [],
    }, 
    formId: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      TwoNum: false,
      call_res: {},
      editingKey: '',
      default_contact_type: '0901201',
      current_contact_type: '0901201',
      form: this.$form.createForm(this),
      CustomerConsult: {
        //客户咨询下拉系列
        contactDetails: [], //联系方式
      },
      operation_type: 'edit',
      memberLoading: false,
      columns: [
        // {
        //   title: '联系方式',
        //   dataIndex: 'contactType',
        //   key: 'contactType',
        //   width: '17%',
        //   scopedSlots: { customRender: 'contactType' },
        // },
        {
          title: '计算单位',
          dataIndex: 'Unit',
          key: 'Unit',
          width: '20%',
          scopedSlots: { customRender: 'Unit' },
        },
        {
          title: '单位进制',
          dataIndex: 'UnitBase',
          key: 'UnitBase',
          width: '17%',
          scopedSlots: { customRender: 'UnitBase' },
        },
        {
          title: '是否基本单位',
          dataIndex: 'recorder',
          key: 'recorder',
          width: '13%',
          scopedSlots: { customRender: 'recorder' },
        },
        {
          title: '规格',
          dataIndex: 'recordDate',
          key: 'recordDate',
          width: '17%',
          scopedSlots: { customRender: 'recordDate' },
        },
        {
          title: '单位单价',
          dataIndex: 'price',
          key: 'price',
          width: '17%',
          scopedSlots: { customRender: 'price' },
        },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'operation' }, width: 150 },
      ],
      data: [
        {
          unitMeasurement:'件',
          systemRatio: '1',
          spec: '',
          price: 0,
          isBasicUnit:1
        }
      ],
      add_edit_state: 0,
    }
  },
   
  watch: {
    ContactList(val) {
      this.data = val
      this.data = this.data.map((item) => ({ ...item, editable: false }))
      // console.log('子组件接受的联系方式数据',this.data)
    },
    customerCrmId(val) {
      return val
    },
    customer(val) {
      return val
    },
    formData(val){ 
      if(val.length > 0){
        for(let i in val){   
          val[i].isBasicUnit = Number(val[i].isBasicUnit) 
        }
        this.data = val
        console.log(this.data)
      }else{
        this.data = []
      }
    },
    formId(val){
      return val
    }
  },
  created() {
    if(this.formData.length > 0){
      
      for(let i in this.formData){   
        this.formData[i].isBasicUnit = Number(this.formData[i].isBasicUnit) 
      }
      this.data = this.formData
    }
    console.log(this.formData)
    
    /**
     下拉接口集合
     * */
    getCustomerConsult().then((res) => {
      // console.log('联系方式接口',res)
      this.CustomerConsult = res
    })
  },
  ...mapState({
    equipment_status: (state) => state.phoneBox.equipment.status,
    connect_status: (state) => state.phoneBox.connect.status,
  }),
  methods: { 
    
    // 新增 
    newMemberData(){ 
      this.data.push({
        unitMeasurement:'件',
        systemRatio: '1',
        spec: '',
        price: 0,
        isBasicUnit:this.data.length > 0 ? 0 : 1 
      })
    },
    // 移除
    removeList(data,index){  
      if(this.data.length > 1){
        if(this.data[index].isBasicUnit == 1){
          this.data.splice(index,1)
          this.data[0].isBasicUnit = 1
        }else{
          this.data.splice(index,1)
        }
  
      }else{
        this.$message.error('至少要有一条产品记录')
      }
      
      
      
    },
    valChange(data,index,t){  
       
      if(t == 'isBasicUnit' ){ 
        for(let i in this.data){  
          this.data[i].isBasicUnit = 0
        } 
        this.data[index].isBasicUnit = (this.data.length>1?data:1)
        
        let boolF = this.data.find(item => {
          return item.isBasicUnit == 1
        })
        if(!boolF){
          this.data[0].isBasicUnit = 1
        }
      }else if(t == 'price'){
        console.log(data)
        if(data == '' || data == null){
          this.data[index].price = 0
        }
      }

      let setData = this.data.map(item => {
        item.unitMeasurement == '' ? item.unitMeasurementBorder = true:item.unitMeasurementBorder = false
        item.systemRatio == '' ? item.systemRatioBorder = true : item.systemRatioBorder = false
        item.spec == '' ? item.specBorder = true : item.specBorder = false 
        return item
      }) 
      this.data = setData
    },
    changeUnitadd(c){
      console.log(c)
    },
    /**
    拨打电话
     * */
    clickCallPhone(record) {
      if (!this.connect_status || !this.equipment_status) {
        this.$message.info('未连接设备')
        return
      }
      console.log('2222', record)
      console.log('333', this.customer)
      const contactContent = record.contactContent
      const name = this.customer.name
      const customerId = record.customerId
      const ccid = window.localStorage.getItem('ccid')
      const params = {
        sendTel: contactContent,
        customerName: name,
        customerId: customerId,
        ccid: ccid,
      }
      callPhone(params).then((res) => {
        console.log('拨打电话结果为', res)
        const data = res.data
        this.$store.commit('phoneBox/setCustomer', data)
        if (!data.switchCard) {
          Bus.$emit('OnDial', { contactContent, type: false })
        } else {
          Bus.$emit('OnCBSwitchNext')
          setTimeout(() => {
            Bus.$emit('OnDial', { contactContent, type: false })
          }, 1000)
        }
      })
    },
    /**
     表单校验手机号
     * */
    validatorPhone(rule, value, callback) {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback('必须为11位数字！')
      }
      callback()
    },
    /**
     表单校验固定电话
     * */
    validatorTel(rule, value, callback) {
      const reg = /^(\d{3,4}-)?\d{7,8}$/
      if (!reg.test(value)) {
        callback('格式不正确')
      }
      callback()
    },
    /**
     表单校验QQ号码
     * */
    validatorQQ(rule, value, callback) {
      const reg = /^[1-9][0-9]{4,10}$/gim
      if (!reg.test(value)) {
        callback('必须为5-11位')
      }
      callback()
    },
    /**
     表单校验微信号
     * */
    validatorWX(rule, value, callback) {
      const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
      if (!reg.test(value)) {
        callback('请填写正确的微信号！')
      }
      callback()
    },
    /**
     表单校验传真
     * */
    validatorFax(rule, value, callback) {
      // const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
      const reg = /^(\d{3,4}-)?\d{7,8}$/
      if (!reg.test(value)) {
        callback('格式不正确')
      }
      callback()
    },
    /**
     表单校验邮箱
     * */
    validatorEmail(rule, value, callback) {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!reg.test(value)) {
        callback('邮箱格式不正确')
      }
      callback()
    },
    /**
     新增一行
     * */
    newMember() {
      console.log(this.data)
      this.TwoNum = true
      this.add_edit_state = 2
      this.current_contact_type = this.default_contact_type
      // const len = this.data.length
      // if (len > 0 && this.data[len - 1].isNew) {
      //   this.$message.warning('当前新增记录已存在！')
      //   return
      // }
      // this.$refs.contact_table_ref.scrollIntoView()
      this.operation_type = 'add'
      this.data.push({
        id: '',
        editable: true,
        isNew: true,
        contactContent: '',
        contactType: '',
        remark: null,
        clientId: '',
        recorder: '',
        recordDate: '',


        Unit:'',
        UnitBase:'',  
        price:''
      })
      this.$nextTick(() => {
        const container = document.getElementById('ref_table') // 获取对象
        container.scrollTop = container.scrollHeight // 滚动高度
        // this.$refs.ref_table.scrollTop = this.$refs.ref_table.scrollHeight
      })
    },
    /**
     改变联系方式
     * */
    changeContact(value, id, column, index) {
      console.log('改变联系方式', value)
      this.current_contact_type = value
      const newData = [...this.data]
      const target = newData.find((item) => id === item.id)
      const contactContent = target.contactContent
      if (target) {
        target[column] = value
        this.data = newData
      }
      let message = ''
      let error_flag = false
      switch (value) {
        case '0901201':
          //移动电话
          const reg_phone = /^1[3456789]\d{9}$/
          if (!reg_phone.test(contactContent)) {
            message = '必须为11位数字！'
            error_flag = true
          }
          break
        case '0901202':
          //固定电话
          const reg_tel = /^(\d{3,4}-)?\d{7,8}$/
          if (!reg_tel.test(contactContent)) {
            message = '固定电话格式不正确！'
            error_flag = true
          }
          break
        case '0901203':
          //传真
          const reg_Fax = /^(\d{3,4}-)?\d{7,8}$/
          if (!reg_Fax.test(contactContent)) {
            message = '传真格式不正确！'
            error_flag = true
          }
          break
        case '0901204':
          //QQ
          const reg_QQ = /^[1-9][0-9]{4,10}$/gim
          if (!reg_QQ.test(contactContent)) {
            message = '必须为5-11位！'
            error_flag = true
          }
          break
        case '0901205':
          //微信
          const reg_wechat = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
          if (!reg_wechat.test(contactContent)) {
            message = '微信格式不正确！'
            error_flag = true
          }
          break
        case '0901206':
          //邮箱
          const reg_email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          if (!reg_email.test(contactContent)) {
            message = '邮箱格式不正确！'
            error_flag = true
          }
          break
      }
    },
    handleChange(value, id, column) {
       

      const newData = [...this.data]
      const target = newData.find((item) => id === item.id)

      if (target) {
        target[column] = value
        this.data = newData
      }

      console.log(value, id, column, this.data) 
    },

    remove(id) {
      const newData = this.data.filter((item) => item.id !== id)
      this.data = newData
      this.add_edit_state = 0
    },
    /**
     保存数据
     * */
    saveRow(record, type, index) {
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        if (errors) {
          console.log('表单检验未通过111', errors)
          return
        }
        console.log('表单检验通过222', values)
        this.memberLoading = true
        const { id } = record
        const target = this.data.find((item) => item.id === id)
        const contactObj = this.CustomerConsult.contactDetails.find((item) => item.name === target.contactType)
        const contactType = contactObj ? contactObj.id : target.contactType
        let parmas
        if (type == 'edit') {
          console.log('编辑')
          parmas = {
            id: target.id,
            clientId: target.customerId,
            contactType: contactType,
            contactContent: target.contactContent,
            recorder: target.recorder,
            recordDate: target.recordDate,
            remark: target.remark,
          }
        }
        if (type == 'add') {
          parmas = {
            clientId: this.customerCrmId,
            contactType: contactType ? contactType : this.default_contact_type,
            contactContent: target.contactContent,
            remark: target.remark,
          }
          console.log('增加', parmas)
        }
        UpdateContact(parmas)
          .then((res) => {
            console.log('联系方式请求结果为', res)
            if (res.code == 200) {
              this.$message.success(type == 'add' ? '添加成功' : '修改成功')
              this.$emit('reLoad')
              this.add_edit_state = 0
            } else {
              this.$message.info(res.message)
              if (type == 'edit') {
                this.cancel(target.id)
                target.editable = false
              }
            }
          })
          .finally(() => {
            this.memberLoading = false
            this.editingKey = ''
          })
      })
    },
    //点击编辑
    toggle(record, index) {
      this.add_edit_state = 1
      const contactObj = this.CustomerConsult.contactDetails.find((item) => item.name === record.contactType)
      this.current_contact_type = contactObj.id
      const id = record.id
      this.editingKey = id
      this.operation_type = 'edit'
      const target = this.data.find((item) => item.id === id)
      this.$nextTick(() => {
        // setTimeout(() => {
        //   this.form.setFieldsValue({
        //     [`phone${index}`]: target.contactContent,
        //   })
        // })
      })

      target._originalData = { ...target }
      target.editable = !target.editable

      setTimeout(() => {
        //光标定位在末尾
        this.$nextTick(() => {
          const length = target.contactContent.length
          const input_ref = `input_${this.current_contact_type}_${index}`
          this.$refs[input_ref].focus()
        })
      })
    },
    getRowByKey(id, newData) {
      const data = this.data
      return (newData || data).find((item) => item.id === id)
    },
    cancel(id) {
      const target = this.data.find((item) => item.id === id)
      this.editingKey = ''
      Object.keys(target).forEach((id) => {
        target[id] = target._originalData[id]
      })
      target._originalData = undefined
      this.add_edit_state = 0
    },
  },
}
</script>

<style lang="less" scoped>
.ant-table-wrapper {
  margin: 0 !important;
}
/deep/ .ant-form-inline .ant-form-item-with-help {
  margin-bottom: -15px;
}
.table-new-add-row {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 24px;
}
.table-new-add-row-border {
  border-color: #3399ff;
  color: #3399ff; 
}

/deep/ .colorBorder>.ant-input,
.colorBorder>.ant-input-number{
  border-color: red !important;
}
.box-header{
  width: 100%;
  padding: 10px; 
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  span{
    color: #000;
    /* padding: 0 36px; */
    width: 124px;
    display: block;
    text-align: center;
  }
}
.content-box{
  height: 170px;
  overflow: auto;
}
.box-content{
  display: flex;
  width: 100%;
  padding: 10px; 
  span{
    padding: 0 5px;
    color: #000;
    /* padding: 0 36px; */
    width: 124px;
    display: block;
    text-align: center;
    line-height: 30px;
  }
}
</style>